import { NextResponse } from 'next/server'
import { Spot } from '@binance/connector'

// === 工具函数：指标计算 ===

// 移动平均
function SMA(data: number[], period: number) {
    const result: number[] = []
    for (let i = 0; i < data.length; i++) {
        if (i < period - 1) result.push(NaN)
        else {
            const sum = data.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0)
            result.push(sum / period)
        }

        
    }
    return result
}

// 指数移动平均
function EMA(data: number[], period: number) {
    const k = 2 / (period + 1)
    const ema: number[] = []
    let prevEma = data[0]
    for (let i = 0; i < data.length; i++) {
        const val = i === 0 ? data[0] : data[i] * k + prevEma * (1 - k)
        ema.push(val)
        prevEma = val
    }
    return ema
}

// RSI
function RSI(data: number[], period: number) {
    const gains: number[] = []
    const losses: number[] = []
    for (let i = 1; i < data.length; i++) {
        const diff = data[i] - data[i - 1]
        gains.push(diff > 0 ? diff : 0)
        losses.push(diff < 0 ? -diff : 0)
    }

    const avgGain = SMA(gains, period)
    const avgLoss = SMA(losses, period)

    const rsi: number[] = [NaN]
    for (let i = 1; i < data.length; i++) {
        const rs = avgLoss[i - 1] === 0 ? 100 : avgGain[i - 1] / avgLoss[i - 1]
        rsi.push(100 - 100 / (1 + rs))
    }
    return rsi
}

// MACD
function MACD(data: number[], short = 12, long = 26, signal = 9) {
    const emaShort = EMA(data, short)
    const emaLong = EMA(data, long)
    const dif = emaShort.map((v, i) => v - emaLong[i])
    const dea = EMA(dif, signal)
    const macd = dif.map((v, i) => (v - dea[i]) )
    return { dif, dea, macd }
}

// BOLL (布林带)
function BOLL(data: number[], period = 20, k = 2) {
    const ma = SMA(data, period)
    const upper: number[] = []
    const lower: number[] = []
    for (let i = 0; i < data.length; i++) {
        if (i < period - 1) {
            upper.push(NaN)
            lower.push(NaN)
            continue
        }
        const slice = data.slice(i - period + 1, i + 1)
        const std = Math.sqrt(slice.reduce((a, b) => a + Math.pow(b - ma[i], 2), 0) / period)
        upper.push(ma[i] + k * std)
        lower.push(ma[i] - k * std)
    }
    return { ma, upper, lower }
}

export async function POST(request: Request) {
    try {
        const { symbol = 'BTCUSDT', limit = 200 } = await request.json()
        console.log(symbol, "symbolsymbol");

        const client = new Spot()
      const intervals = ['1m', '3m', '15m', '1h', '4h', '12h', '1d', '3d', '1w']


        const result: Record<string, any> = {}

        for (const interval of intervals) {
            const { data } = await client.klines(symbol, interval, { limit })

            const closes = data.map((k: any[]) => parseFloat(k[4]))
            const volumes = data.map((k: any[]) => parseFloat(k[5]))

            const ema20 = EMA(closes, 20)
            const { dif, dea, macd } = MACD(closes)
            const rsi14 = RSI(closes, 14)
            const boll = BOLL(closes, 20, 2)

            result[interval] = {
                lastClose: closes.at(-1),
                lastVolume: volumes.at(-1),
                EMA20: ema20.at(-1),
                MACD: macd.at(-1),
                DIF: dif.at(-1),
                DEA: dea.at(-1),
                RSI14: rsi14.at(-1),
                BOLL: {
                    upper: boll.upper.at(-1),
                    middle: boll.ma.at(-1),
                    lower: boll.lower.at(-1)
                }
            }
        }

        return NextResponse.json({ success: true, symbol, data: result })

    } catch (err) {
        console.error('Error fetching indicators:', err)
        return NextResponse.json({
            success: false,
            message: err instanceof Error ? err.message : String(err)
        }, { status: 500 })
    }
}
